/**
 * VUEshop
 * ============================================================================
 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.vueshop.com.cn
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: soubao-java 2020-07-22 $
 */<template>
  <div>
    <div
      id="explanation"
      class="explanation"
      style="color: rgb(85, 85, 85); background-color: rgb(243, 244, 244); width: 98%; height: 100%;"
    >
      <div class="bckopa-tips">
        <div class="title">
          <img src="@/static/images/handd.png" alt />
          <h4 title="提示相关设置操作时应注意的要点">操作提示</h4>
        </div>
        <ul>
          <li>在此添加关键字, 用户发送关键词与之匹配时自动回复</li>
        </ul>
      </div>
      <span title="收起提示" id="explanationZoom" style="display: block;"></span>
    </div>
    <div class="mDiv">
      <div class="ftitle">
        <h3>关键词回复列表</h3>
        <h5>(共 {{totalCount}} 条记录)</h5>
      </div>
      <div class="fbutton">
        <div class="add" @click="editKeyword()">
          <span>
            <i class="el-icon-circle-plus" /> 添加关键词回复
          </span>
        </div>
      </div>
      <a href @click.prevent="refresh()" class="refresh-date">
        <div title="刷新数据" class="pReload">
          <i class="fa fa-refresh"></i>
        </div>
      </a>
    </div>
    <div class="tablebox" v-if="tableData">
      <el-table :data="tableData" style="width: 100%;">
        <el-table-column label="关键词" prop="keyword" width="150"></el-table-column>
        <el-table-column label="回复类型" prop="msg_type" width="120">
          <template slot-scope="scope">
            <label v-if="scope.row.msg_type == 'text'">文本</label>
            <label v-else-if="scope.row.msg_type == 'news'">图文</label>
            <label v-else-if="scope.row.msg_type == 'image'">图片</label>
            <label v-else-if="scope.row.msg_type == 'video'">视频</label>
            <label v-else-if="scope.row.msg_type == 'voice'">音频</label>
          </template>
        </el-table-column>
        <el-table-column label="内容" prop="content" width="320" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button-group>
              <el-button size="small" @click="editKeyword(scope.row)" icon="el-icon-edit-outline">编辑</el-button>
              <el-button size="small" @click="remove(scope.row.id)" icon="el-icon-delete">删除</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="centerDialogVisible"
      width="650px"
      center
      :modal-append-to-body="false"
      @close="dialogClose()"
    >
      <el-form ref="form" :rules="rules" :model="form" label-width="100px">
        <el-form-item label="关键词" prop="keyword">
          <el-input v-model="form.keyword" size="small" class="keyword">
            <template slot="prepend">
              <el-select v-model="form.match" class="match">
                <el-option
                  v-for="item in matchs"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </template>
          </el-input>
          <p class="notic">多个关键词，请以英文逗号隔开( , )</p>
        </el-form-item>
        <el-form-item label="回复类型">
          <el-radio-group v-model="form.msg_type">
            <el-radio label="text">文字</el-radio>
            <label class="el-radio" @click="showMaterial('news')">
              <el-radio label="news">图文</el-radio>
            </label>
            <label class="el-radio" @click="showMaterial('image')">
              <el-radio label="image">图片</el-radio>
            </label>
            <label class="el-radio" @click="showMaterial('video')">
              <el-radio label="video">视频</el-radio>
            </label>
            <label class="el-radio" @click="showMaterial('voice')">
              <el-radio label="voice">音频</el-radio>
            </label>
          </el-radio-group>
          <p class="notic">注意：关键字图文消息回复只能回复一条，也就是选择图文素材的第一条图文</p>
        </el-form-item>
        <el-form-item label="回复内容">
          <el-input
            v-if="form.msg_type == 'text'"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 6}"
            placeholder="自动回复内容"
            v-model="form.content"
            size="small"
          ></el-input>
          <div
            v-else-if="msgType == 'news'"
            class="ma-card news-border"
            style="text-align:center"
            @click="showMaterial('news')"
          >
            <i v-if="!material.wx_news_list" class="el-icon-plus avatar-uploader-icon" />
            <div v-else-if="material.wx_news_list.length == 1">
              <!--单图文-->
              <div class="title ellipsis-1">{{material.wx_news_list[0].title}}</div>
              <div class="time">{{material.update_time | datefmtAll}}</div>
              <div class="card-item no-line">
                <div class="cover">
                  <img :src="material.wx_news_list[0].thumb_url" />
                </div>
              </div>
              <div
                class="desc ellipsis-2"
              >{{material.wx_news_list[0].digest ? material.wx_news_list[0].digest : material.wx_news_list[0].content_digest}}</div>
            </div>
            <div v-else>
              <!--多图文-->
              <div class="time">{{material.update_time | datefmtAll}}</div>
              <div v-for="(item,index) in material.wx_news_list">
                <div class="card-item">
                  <div v-if="index==0" class="cover cover-sm">
                    <img :src="item.thumb_url" />
                    <div class="title-in ellipsis-1">{{item.title}}</div>
                  </div>
                  <div v-else class="post">
                    <div class="post-title ellipsis-2">{{item.title}}</div>
                    <div class="post-cover">
                      <img :src="item.thumb_url" />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div
            v-else-if="msgType == 'image'"
            class="ma-card"
            style="text-align:center"
            @click="showMaterial('image')"
          >
            <i v-if="!material.path" class="el-icon-plus avatar-uploader-icon" />
            <div v-else>
              <div class="title ellipsis-1">{{material.name}}</div>
              <div class="time">{{material.update_time | datefmtAll}}</div>
              <div class="card-item no-line">
                <el-image :src="material.path" fit="scale-down" style="height:200px" />
              </div>
            </div>
          </div>
          <div
            v-else-if="msgType == 'video'"
            class="ma-card"
            style="text-align:center; width:330px"
            @click="showMaterial('video')"
          >
            <i v-if="!material.path" class="el-icon-plus avatar-uploader-icon" />
            <div v-else>
              <div class="title ellipsis-1">{{material.name}}</div>
              <div class="time">{{material.update_time | datefmtAll}}</div>
              <div class="card-item no-line">
                <video
                  v-if="material.path"
                  :src="material.path"
                  width="320"
                  height="180"
                  autoplay
                  controls="controls"
                  ref="multimedia"
                ></video>
              </div>
            </div>
          </div>
          <div
            v-else-if="msgType == 'voice'"
            class="ma-card"
            style="text-align:center; width:310px"
            @click="showMaterial('voice')"
          >
            <i v-if="!material.path" class="el-icon-plus avatar-uploader-icon" />
            <div v-else>
              <div class="title ellipsis-1">{{material.name}}</div>
              <div class="time">{{material.update_time | datefmtAll}}</div>
              <div class="card-item no-line">
                <audio
                  v-if="material.path"
                  :src="material.path"
                  autoplay
                  controls="controls"
                  ref="multimedia"
                ></audio>
              </div>
            </div>
          </div>
          <p class="err-msg" v-if="errResult.reply_content">{{errResult.reply_content}}</p>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmit('form')" :loading="isLoading">保 存</el-button>
      </span>
    </el-dialog>

    <!-- 图文素材选择dialog -->
    <el-dialog
      title="选择图文素材"
      :visible.sync="newsMaterialDialogVisible"
      width="1250px"
      center
      :modal-append-to-body="false"
    >
      <div class="ma-list" v-if="msgType == 'news'">
        <div class="ma-card news-border" v-for="news in materialList" @click="selectMaterial(news)">
          <div v-if="news.wx_news_list.length == 1">
            <!--单图文-->
            <div class="title ellipsis-1">{{news.wx_news_list[0].title}}</div>
            <div class="time">{{news.update_time | datefmtAll}}</div>
            <div class="card-item no-line">
              <div class="cover">
                <img :src="news.wx_news_list[0].thumb_url" />
              </div>
            </div>
            <div
              class="desc ellipsis-2"
            >{{news.wx_news_list[0].digest ? news.wx_news_list[0].digest : news.wx_news_list[0].content_digest}}</div>
          </div>
          <div v-else>
            <!--多图文-->
            <div class="time">{{news.update_time | datefmtAll}}</div>
            <div v-for="(item,index) in news.wx_news_list">
              <div class="card-item">
                <div v-if="index==0" class="cover cover-sm">
                  <img :src="item.thumb_url" />
                  <div class="title-in ellipsis-1">{{item.title}}</div>
                </div>
                <div v-else class="post">
                  <div class="post-title ellipsis-2">{{item.title}}</div>
                  <div class="post-cover">
                    <img :src="item.thumb_url" />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <el-pagination
        background
        class="paginationbox"
        @size-change="handleSizeChangeNews"
        @current-change="handleCurrentChangeNews"
        :current-page="currentPageNews"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSizeNews"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCountNews"
      ></el-pagination>
    </el-dialog>

    <!-- 图片素材选择dialog -->
    <el-dialog
      title="选择图片素材"
      :visible.sync="imageMaterialDialogVisible"
      width="1250px"
      center
      :modal-append-to-body="false"
    >
      <div class="ma-list" v-if="msgType == 'image'">
        <div class="ma-card" v-for="image in materialList" @click="selectMaterial(image)">
          <div class="news-border">
            <div class="title ellipsis-1">{{image.name}}</div>
            <div class="time">{{image.update_time | datefmtAll}}</div>
            <div class="card-item no-line">
              <el-image :src="image.path" fit="scale-down" style="width:200px;height:200px" />
            </div>
          </div>
        </div>
      </div>
      <el-pagination
        background
        class="paginationbox"
        @size-change="handleSizeChangeImage"
        @current-change="handleCurrentChangeImage"
        :current-page="currentPageImage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSizeImage"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCountImage"
      ></el-pagination>
    </el-dialog>

    <!-- 视频素材选择dialog -->
    <el-dialog
      title="选择视频素材"
      :visible.sync="videoMaterialDialogVisible"
      width="1250px"
      center
      :modal-append-to-body="false"
      @close="dialogClose()"
    >
      <div class="ma-list" v-if="msgType == 'video'">
        <div
          class="ma-card"
          style="width:330px"
          v-for="video in materialList"
          @click="selectMaterial(video)"
        >
          <div class="news-border">
            <div class="title ellipsis-1">{{video.name}}</div>
            <div class="time">{{video.update_time | datefmtAll}}</div>
            <div class="card-item no-line">
              <video
                v-if="video.path"
                :src="video.path"
                width="320"
                height="180"
                controls="controls"
                ref="multimediaList"
              ></video>
            </div>
          </div>
        </div>
      </div>
      <el-pagination
        background
        class="paginationbox"
        @size-change="handleSizeChangeVideo"
        @current-change="handleCurrentChangeVideo"
        :current-page="currentPageVideo"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSizeVideo"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCountVideo"
      ></el-pagination>
    </el-dialog>

    <!-- 音频素材选择dialog -->
    <el-dialog
      title="选择音频素材"
      :visible.sync="voiceMaterialDialogVisible"
      width="1250px"
      center
      :modal-append-to-body="false"
      @close="dialogClose()"
    >
      <div class="ma-list" v-if="msgType == 'voice'">
        <div
          class="ma-card"
          style="width:310px"
          v-for="voice in materialList"
          @click="selectMaterial(voice)"
        >
          <div class="news-border">
            <div class="title ellipsis-1">{{voice.name}}</div>
            <div class="time">{{voice.update_time | datefmtAll}}</div>
            <div class="card-item no-line">
              <audio v-if="voice.path" :src="voice.path" controls="controls" ref="multimediaList"></audio>
            </div>
          </div>
        </div>
      </div>
      <el-pagination
        background
        class="paginationbox"
        @size-change="handleSizeChangeVoice"
        @current-change="handleCurrentChangeVoice"
        :current-page="currentPageVoice"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSizeVoice"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCountVoice"
      ></el-pagination>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAutoReplyKeywordPage,
  addAutoReply,
  updateAutoReply,
  removeReply,
  getMaterialPage,
  getMaterial,
} from "@/utils/api";
export default {
  data() {
    return {
      tableData: [],
      totalCount: 0,
      totalCountNews: 0,
      totalCountImage: 0,
      totalCountVideo: 0,
      totalCountVoice: 0,
      centerDialogVisible: false,
      newsMaterialDialogVisible: false,
      imageMaterialDialogVisible: false,
      videoMaterialDialogVisible: false,
      voiceMaterialDialogVisible: false,
      form: { type: "keyword", msg_type: "text", match: 0 },
      msgType: "text",
      material: {}, //编辑时原本的自动回复素材对象
      materialList: [], //可选素材分页数据
      canLoad: true, //标识，解决单选框触发两次方法问题
      dialogTitle: "",
      isLoading: false,
      errResult: {},
      matchs: [
        { label: "半匹配", value: 0 },
        { label: "全匹配", value: 1 },
      ],
      currentPage: this.$route.params.currentPage || 1,
      currentPageNews: 1,
      currentPageImage: 1,
      currentPageVideo: 1,
      currentPageVoice: 1,
      pageSize: 10,
      pageSizeNews: 10,
      pageSizeImage: 10,
      pageSizeVideo: 10,
      pageSizeVoice: 10,
      rules: {
        keyword: [
          {
            required: true,
            message: "请输入关键字",
            trigger: "blur",
          },
          {
            maxlmmength: 10,
            message: "请输入关键字",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getPage();
  },
  methods: {
    handleSizeChange(e) {
      this.pageSize = e;
      this.getPage();
    },
    handleSizeChangeNews(e) {
      this.pageSizeNews = e;
      this.getMaterialPage();
    },
    handleSizeChangeImage(e) {
      this.pageSizeImage = e;
      this.getMaterialPage();
    },
    handleSizeChangeVideo(e) {
      this.pageSizeVideo = e;
      this.getMaterialPage();
    },
    handleSizeChangeVoice(e) {
      this.pageSizeVoice = e;
      this.getMaterialPage();
    },
    handleCurrentChange(e) {
      this.currentPage = e;
      this.getPage();
    },
    handleCurrentChangeNews(e) {
      this.currentPageNews = e;
      this.getMaterialPage();
    },
    handleCurrentChangeImage(e) {
      this.currentPageImage = e;
      this.getMaterialPage();
    },
    handleCurrentChangeVideo(e) {
      this.currentPageVideo = e;
      this.getMaterialPage();
    },
    handleCurrentChangeVoice(e) {
      this.currentPageVoice = e;
      this.getMaterialPage();
    },
    getPage() {
      var that = this;
      getAutoReplyKeywordPage({
        type: "keyword",
        page: that.currentPage,
        size: that.pageSize,
      }).then((res) => {
        that.tableData = res.records;
        that.totalCount = res.total;
      });
    },
    refresh() {
      this.getPage();
      this.$message.success("刷新成功！");
    },
    editKeyword(row) {
      if (row) {
        this.form = JSON.parse(JSON.stringify(row));
        this.msgType = row.msg_type;
        if (row.type != "text") {
          this.getMaterial(row.material_id);
        }
        this.dialogTitle = "关键词自动回复编辑";
      } else {
        this.form = { type: "keyword", msg_type: "text", match: 0 };
        this.dialogTitle = "关键词自动回复添加";
      }
      this.centerDialogVisible = true;
    },
    showMaterial(type) {
      this.form.msg_type = type;
      this.material = {};
      if (type == "news") {
        this.newsMaterialDialogVisible = true;
      } else if (type == "image") {
        this.imageMaterialDialogVisible = true;
      } else if (type == "video") {
        this.videoMaterialDialogVisible = true;
      } else if (type == "voice") {
        this.voiceMaterialDialogVisible = true;
      }
      if (this.canLoad) {
        let that = this;
        this.canLoad = false;
        setTimeout(function () {
          that.canLoad = true;
        }, 500);
        this.getMaterialPage();
      }
    },
    selectMaterial(material) {
      this.material = material;
      this.form.content = null;
      this.form.material_id = material.id;
      this.newsMaterialDialogVisible = false;
      this.imageMaterialDialogVisible = false;
      this.videoMaterialDialogVisible = false;
      this.voiceMaterialDialogVisible = false;
    },
    dialogClose() {
      if (this.$refs.multimedia) {
        this.$refs.multimedia.pause();
      }
      if (this.$refs.multimediaList) {
        this.$refs.multimediaList.forEach((e) => {
          e.pause();
        });
      }
    },
    getMaterial(materialId) {
      let that = this;
      getMaterial({ id: materialId }).then((res) => {
        that.material = res;
      });
    },
    getMaterialPage() {
      let type = this.form.msg_type;
      let params = { type: type };
      if (type == "news") {
        params.page = this.currentPageNews;
        params.size = this.pageSizeNews;
      } else if (type == "image") {
        params.page = this.currentPageImage;
        params.size = this.pageSizeImage;
      } else if (type == "video") {
        params.page = this.currentPageVideo;
        params.size = this.pageSizeVideo;
      } else if (type == "voice") {
        params.page = this.currentPageVoice;
        params.size = this.pageSizeVoice;
      }
      let that = this;
      getMaterialPage(params).then((res) => {
        if (res.msg) {
          that.$message.error(res.msg);
        } else {
          that.materialList = res.records;
          that.msgType = type; //请求成功后更改此参数，用于展示数据
          if (type == "news") {
            that.totalCountNews = res.total;
          } else if (type == "image") {
            that.totalCountImage = res.total;
          } else if (type == "video") {
            that.totalCountVideo = res.total;
          } else if (type == "voice") {
            that.totalCountVoice = res.total;
          }
          that.$forceUpdate();
        }
      });
    },
    onSubmit(formName) {
      let check = true;
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          check = false;
          return false;
        }
      });
      if (this.form.msg_type == "text" && !this.form.content) {
        this.errResult.reply_content = "请输入回复内容";
        check = false;
      } else if (!this.form.material_id) {
        if (this.form.msg_type == "news") {
          this.errResult.reply_content = "请选择回复的图文素材";
          check = false;
        } else if (this.form.msg_type == "image") {
          this.errResult.reply_content = "请选择回复的图片素材";
          check = false;
        } else if (this.form.msg_type == "video") {
          this.errResult.reply_content = "请选择回复的视频素材";
          check = false;
        } else if (this.form.msg_type == "voice") {
          this.errResult.reply_content = "请选择回复的音频素材";
          check = false;
        }
      }
      if (!check) {
        this.$message.error("参数错误");
        this.$forceUpdate();
        return;
      }
      let that = this;
      this.isLoading = true;
      if (this.form.id) {
        updateAutoReply(this.form).then((res) => {
          if (res.status == 1) {
            that.$message.success("更新成功");
            that.centerDialogVisible = false;
            that.getPage();
          } else {
            that.$message.error(res.msg);
          }
          that.isLoading = false;
        });
      } else {
        addAutoReply(this.form).then((res) => {
          if (res.status == 1) {
            that.$message.success("保存成功");
            that.centerDialogVisible = false;
            that.getPage();
          } else {
            that.$message.error(res.msg);
          }
          that.isLoading = false;
        });
      }
    },
    remove(id) {
      var that = this;
      this.$confirm("确认删除？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          removeReply({ id: id }).then(function (res) {
            if (res.status == 1) {
              that.getPage();
              that.$message.success("删除成功!");
            }
          });
        })
        .catch(() => {
          that.$message.info("已取消删除");
        });
    },
  },
};
</script>

<style scoped>
@import "../../../../static/css/weixin-mp.css";

.news-border:hover {
  border: 1px #a2a2d6 solid;
}
>>> .keyword .el-input__inner {
  width: 348px;
}
>>> .match .el-input__inner {
  width: 100px;
}
.ma-card .btns .btn {
  width: 100%;
}
.avatar-uploader-icon {
  line-height: 100px;
}
</style>
